import java.io.*;
import java.net.*;

import org.mybeans.dao.DAOException;

import databeans.UserBean;

import model.UserDAO;

public class clientThread extends Thread{
	DataInputStream is = null;
	PrintStream os = null;
	Socket clientSocket = null;
        
	private BufferedReader fromClient;
	
	public static String LogInCommand = "DroidChat:LogIn";
	public static String RegisterCommand = "DroidChat:Register";
	
	private UserDAO userDAO;
	
	public clientThread(Socket clientSocket, UserDAO userDAO){
		this.clientSocket = clientSocket;
		this.userDAO = userDAO;
	}
        
	public void run(){
		String clientCommand;
		InetAddress clientAdrress = clientSocket.getInetAddress();
		try{
			is = new DataInputStream(clientSocket.getInputStream());
			os = new PrintStream(clientSocket.getOutputStream());
			
			System.out.println("processing a client: " + clientAdrress.getHostAddress());
			
			fromClient = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
			System.out.println(" reading from client");
			clientCommand = fromClient.readLine();
			System.out.println(" done reading from client " + clientCommand);
			
			if(clientCommand.startsWith(LogInCommand)){
				
				System.out.println(" received a Log In Command");
				
				String[] args = clientCommand.split(",");
				
				String loginID = args[1];
				String password = args[2];
				
				System.out.print("DroidChat server recieved userID=" + loginID);
				System.out.println(" , password=" + password);
				
				os.print("A Logged-in Ticket"); // reply with the user with a Login Ticket
				
			}else if(clientCommand.startsWith(RegisterCommand)){
				System.out.println(" received a Register Command");
				
				String[] args = clientCommand.split(",");
				
				String loginID = args[1];
				String password = args[2];
				
				System.out.print("DroidChat server recieved userID=" + loginID);
				System.out.println(" , password=" + password);
				
				if (userDAO.lookup(loginID) != null) {
	                System.out.println("the loginID already exists...");
	                os.print("registration fails - loginID already registered");
	            }else{
	            	UserBean newUser = new UserBean();
	            	newUser.setLoginID(loginID);
	            	newUser.setPassword(password);
	            	
	            	userDAO.create(newUser);
	            	os.print("A Logged-in Ticket"); // reply with the user with a Login Ticket
	            }
			}
			
			is.close();
			os.close();
			clientSocket.close();
		}
		catch(IOException e){} catch (DAOException e) {
			e.printStackTrace();
		};
		System.out.println("done processing a client:" + clientAdrress.getHostAddress());
	}
}